package cn.lblbc.webbrowser

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter

class TabAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
    private val fragments = mutableListOf<Fragment>()
    private val titles = mutableListOf<String>()

    override fun getItemCount(): Int = fragments.size

    override fun createFragment(position: Int): Fragment = fragments[position]

    fun addFragment(fragment: Fragment, title: String = "") {
        fragments.add(fragment)
        titles.add(title)
        notifyItemInserted(fragments.size - 1)
    }

    fun removeFragment(position: Int) {
        if (position in fragments.indices) {
            fragments.removeAt(position)
            titles.removeAt(position)
            notifyItemRemoved(position)
        }
    }

    fun getTitle(position: Int): String {
        return try {
            if (position in titles.indices) titles[position] else ""
        } catch (e: Exception) {
            ""
        }
    }

    fun updateTitle(fragment: Fragment, title: String) {
        try {
            val position = fragments.indexOf(fragment)
            if (position != -1 && position < titles.size) {
                titles[position] = title
            }
        } catch (e: Exception) {
            // 处理可能的异常
        }
    }

    fun getFragment(position: Int): Fragment? {
        return try {
            if (position in fragments.indices) fragments[position] else null
        } catch (e: Exception) {
            null
        }
    }
}